/***************************************************************
*
* ds_ref_vector.cpp  
* 
***************************************************************/

#include "ds_ref_vector.h"


DEFINE_TYPE_ID(refVector)

int dsREF_VECTOR::Count(void){
   return Length();
}

int dsREF_VECTOR::Last(void){
   return Length() - 1;
}

void dsREF_VECTOR::Erase(int iIdx, int iCount){
   dsVECTOR<dsDATA>::Erase(iIdx, iCount);
}
dsDATA dsREF_VECTOR::Get(int iIdx){
   return (*this)[iIdx];

}
void dsREF_VECTOR::Set(int iIdx, const dsDATA &d){
   (*this)[iIdx] = d;
}

void dsREF_VECTOR::Push(const dsDATA &d){
   PushBack(d);
}
void dsREF_VECTOR::Pop(void){
   PopBack();
}
void dsREF_VECTOR::Remove(dsDATA &item){
   for (int i = 0; i < Length(); i++) {
      if (pData[i] == item){
         Erase(i,1);
         break;
      }
   }

}

int dsREF_VECTOR::Find(dsDATA &obj, dsSTRING name, const dsDATA &d)
{
   dsSTRID findId(name.CStr(), false);
   const dsDATA_TYPE *pType = obj.GetType();

   if (!pType->IsFunc(obj, findId)) {
      return -1;
   }

   dsDATA argv[2];
   argv[1] = d;

   for (int i = 0; i < Length(); i++) {
      dsDATA ret;
      argv[0] = pData[i];
      BOOL isSucceded = pType->CallFunc(findId, obj, argv, 2, ret);

      if (!isSucceded) {
         continue;
      }

      bool res;
      if (!ret.GetValue(res)) {
         continue;
      }

      if (res) {
         return i;
      }
   }

   return -1;
}

void dsREF_VECTOR::Sort(dsDATA &obj, dsSTRING sFunc){

   static dsSTRID findId(sFunc.CStr(), false);
   const dsDATA_TYPE *pType = obj.GetType();
   if (pType->IsFunc(obj, findId)) {
      SortCmp cmp(obj,findId);
      dsVECTOR<dsDATA>::Sort(cmp);
   }
}

dsREF_VECTOR::SortCmp::SortCmp(dsDATA &obj,dsSTRID sFunc):
   m_obj(obj),
   m_sFunc(sFunc){

}

int dsREF_VECTOR::SortCmp::cmp(const dsDATA& d1,const dsDATA& d2) const{
   dsDATA ret;
   dsDATA argv[2];
   argv[0] = d1;
   argv[1] = d2;

   const dsDATA_TYPE *pType = m_obj.GetType();
   BOOL isSucceded = pType->CallFunc(m_sFunc, m_obj, argv, 2, ret);
   return *ret.GetPtr<int>();

}
